//
//  UserAccount.swift
//  XDweibo
//
//  Created by HanXingda on 15/6/27.
//  Copyright © 2015年 韩兴达. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccount: NSObject,NSCoding{
    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String
    /// access_token的生命周期，单位是秒数(实际是数值！)
    var expires_in: NSTimeInterval
    /// 当前授权用户的UID
    var uid: String
    var expriesDate: NSDate
    var name: String?
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        uid = dict["uid"] as! String
        expriesDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    
    //加载用户全部信息
    func loadUserInfo(finished:(account: UserAccount?,error: NSError?) -> ()) {
        
        let parames = ["access_token" : access_token,"uid" : uid]
        NetWorkTools.sharedNetworkTools().GET("2/users/show.json", parameters: parames, success: { (_, JSON) -> Void in
            print(JSON)
            let dict = JSON as! [String : AnyObject]
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            self.saveAccount()
            finished(account: self, error: nil)
            }) { (_, error) -> Void in
                print(error)
                finished(account: nil, error: error)
        }
    }
    
    //打印对象信息
   override var description: String {
        let properties = ["access_token", "expires_in", "uid","expriesDate","name","avatar_large"]
    return "\(self.dictionaryWithValuesForKeys(properties))"
}
    
    // MARK: - 加载和保存用户信息
    //拼接沙盒路径
    static let accountPath = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as! String
        expriesDate = aDecoder.decodeObjectForKey("expriesDate") as! NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
   //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expriesDate, forKey: "expriesDate")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //保存用户信息
    func saveAccount() {
        print("保存用户信息")
        print(UserAccount.accountPath)

        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    //加载用户信息
    class func loadAccount() -> UserAccount? {
        print("加载用户信息")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount {
            if account.expriesDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        return nil
    }
}
